var HxBasicGoodsInfoDlg = {
    data: {
		id:"",
        goodsCustomerId: "",
        goodsCustomerName: "",
        goodsName: "",
        goodsNumber: "",
        goodsPcode69: "",
        goodsXcode69: "",
        goodsHelpcode: "",
        goodsSpecs: "",
        goodsBigtype: "",
        goodsBrand: "",
        jibenUnit: "",
        kcUnit: "",
        kcRate: "",
        cgUnit: "",
        cgRate: "",
        pfUnit: "",
        pfRate: "",
        psUnit: "",
        psRate: "",
        anquanNum: "",
        goodsBottom: "",
        goodsLamination: "",
        goodsTraylayer: "",
        goodsSupportvolume: "",
        length: "",
        height: "",
        width: "",
        goodsWeight: "",
        goodsVolume: "",
        goodsChargingCg: "",
        goodsChargingPs: "",
        goodsChargingPf: "",
        goodsWarranty: ""
    }
};
var BasicPutgoodsInfoDlg = {
    data: {
		id:"",
		dictId:"",
        putgoodsCustomerId: "",
        putgoodsOperateName: "",
        putgoodsName: "",
		unitNumber:"",
		unitType:""
    }
};
layui.use(['table', 'admin', 'ax','laydate'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;

    laydate.render({
    	elem:'#startTime'
        	,value:new Date()
    });
    
    laydate.render({
    	elem:'#endTime'
        	,value:new Date()
    });

    /**
     * 入库单表管理
     */
    var HxStoragePut = {
        tableId: "hxStoragePutTable"
    };

    /**
     * 入库单明细表管理
     */
    var HxStoragePutDetailed = {
        tableId: "hxStoragePutDetailedTable"
    };

    /**
     * 初始化表格的列
     */
    HxStoragePut.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {field: 'customerName', sort: true, title: '客户名称'},
            {field: 'storageState', sort: true, title: '单据状态', templet: '#storageStateTpl'},
            {field: 'yuyueTime', sort: true, title: '预约时间'},
            {field: 'storageNumber', sort: true, title: '入库单号', width: 140},
            {field: 'orderType', sort: true, title: '单据类型'},

            {field: 'getWarehouse', sort: true, title: '收货仓库'},
            {field: 'setUnit', sort: true, title: '发货客户', width: 140, totalRowText: '合计：'},

            {field: 'goodsNum', sort: true, title: '商品数',totalRowText: sl.goodsNum},
            {field: 'putNum', sort: true, title: '数量', totalRowText: sl.putNum},
            {field: 'realNum', sort: true, title: '实入数量', totalRow: sl.realNum},
            {field: 'putVolume', sort: true, title: '体积',totalRowText: sl.putVolume},
            {field: 'createTime', sort: true, title: '创建时间'},
            {field: 'createUserName', sort: true, title: '创建人'},
            {field: 'completeTime', sort: true, title: '完成时间'},
            {field: 'notes', sort: true, title: '备注'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    HxStoragePut.search = function () {
        var queryData = {};
        queryData['storageState'] = $("#storageState").val();
        queryData['timeType'] = $("#timeType").val();
        queryData['startTime'] = $("#startTime").val();
        queryData['endTime'] = $("#endTime").val();
        queryData['customerId'] = $("#customerId").val();
        queryData['getWarehouseId'] = $("#getWarehouseId").val();
        queryData['setUnits'] = $("#setUnit").val();
        queryData['condition'] = $("#condition").val();
        queryData['orderType'] = $("#orderType").val();
        queryData['goodsName'] = $("#goodsName").val();
        // table.reload(HxStoragePut.tableId, {
        //     where: queryData, page: {curr: 1},
        //      done:function () {
        //     }
        // });
        $.ajax({
            url:Feng.ctxPath + '/hxStoragePut/count',
            data: queryData, // 将 queryData 作为请求体发送
            dataType:"json",   //返回格式为json
            async: false,
            type:"post",   //请求方式
            success:function(data){
                sl = data.data
                console.log(data);
            }
        });
        var tableResult = table.render({
            elem: '#' + HxStoragePut.tableId,
            url: Feng.ctxPath + '/hxStoragePut/list',
            where: queryData,
            toolbar: '#toolbarfrom',
            cellMinWidth: 100,
            totalRow: true ,//开启合计行
            cols: HxStoragePut.initColumn()
            ,parseData: function(res){ // 数据转换
                return {
                    "code": 0,
                    "msg": res.msg, // 假设原数据中的msg字段存储的是提示信息
                    "count": res.count,
                    "data": $.map(res.data, function(item){ // 假设原数据中的data字段存储的是数据集
                        return {
                            // 假设你想转换的字段是numberField
                            putNum: Number(item.putNum), // 将字符串转换为数字
                            realNum: Number(item.realNum), // 将字符串转换为数字

                            // 其他字段保持不变
                            id: item.id,
                            customerName: item.customerName,
                            storageState: item.storageState,
                            yuyueTime: item.yuyueTime,
                            storageNumber: item.storageNumber,
                            orderType: item.orderType,
                            getWarehouse: item.getWarehouse,
                            setUnit: item.setUnit,
                            goodsNum: item.goodsNum,
                            putVolume: item.putVolume,
                            createTime: item.createTime,
                            createUserName: item.createUserName,
                            completeTime: item.completeTime,
                            notes: item.notes
                        };
                    })
                };
            },
            page: true,
            limit: 40,
            height: 410,
        });
    };


    // 审核回传入库单
    $('#examine').click(function () {
        var checkStatus = table.checkStatus(HxStoragePut.tableId);
        data = checkStatus.data;
        console.log(data);

        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            //请求后台数据请求
            $.ajax({
                type: "POST",
                url: Feng.ctxPath + '/hxStoragePut/btnSubmitExamine?ids='+ids,
                data: {ids: ids},
                dataType: "json",
                success: function (data) {

                        Feng.success("操作成功!"+ data.message + "!");
                        table.reload(HxStoragePut.tableId);

                },
                error: function (data) {
                    Feng.error("操作失败!" + data.responseJSON.message + "!");
                }
            });
        } else {
            layer.alert('请至少选中一条数据');
        }


    });

    // 手动关单
    $('#btnsdwc').click(function () {
        var checkStatus = table.checkStatus(HxStoragePut.tableId);
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            //请求后台数据请求
            $.ajax({
                type: "POST",
                url: Feng.ctxPath + '/hxStoragePut/btnsdwc?ids='+ids,
                data: {ids: ids},
                dataType: "json",
                success: function (data) {
                    Feng.success("操作成功!"+ data.message + "!");
                    table.reload(HxStoragePut.tableId);
                },
                error: function (data) {
                    Feng.error("操作失败!" + data.responseJSON.message + "!");
                }
            });
        } else {
            layer.alert('请至少选中一条数据');
        }
    });


    //点击选择商品名称
    $('#choiceGoods').click(function () {
        layer.open({
            type: 2,
            title: '选择商品',
            area: ['1000px', '500px'],
            content: Feng.ctxPath + '/hxBasicGoods/toChoiceGoods',
            end: function () {
                $("#goodsName").val(HxBasicGoodsInfoDlg.data.goodsName);//商品名称
            }
        });
    });
    
    $('#choiceSetUnit').click(function () {
        layer.open({
            type: 2,
            title: '选择单位',
            area: ['1000px', '500px'],
            content: Feng.ctxPath + '/basicPutgoods/tochoiceBasicPutgoods_hx',
            end: function () {
                $("#setUnit").val(BasicPutgoodsInfoDlg.data.putgoodsName);
            }
        });
    });

    /**
     * 导出excel按钮
     */

    HxStoragePut.exportExcel = function () {
        var checkRows = table.checkStatus(HxStoragePut.tableId);
        if (checkRows.data.length > 0) {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        } else {
            var queryData = {};
            queryData['storageState'] = $("#storageState").val();
            queryData['timeType'] = $("#timeType").val();
            queryData['startTime'] = $("#startTime").val();
            queryData['endTime'] = $("#endTime").val();
            queryData['customerId'] = $("#customerId").val();
            queryData['getWarehouseId'] = $("#getWarehouseId").val();
            queryData['setUnits'] = $("#setUnit").val();
            queryData['condition'] = $("#condition").val();
            queryData['orderType'] = $("#orderType").val();
            queryData['goodsName'] = $("#goodsName").val();
            var startTime= $("#startTime").val();
            var endTime= $("#endTime").val();
            $.ajax({
                type: "POST",
                url: Feng.ctxPath + "/hxStoragePut/listAll",
                dataType:'json',
                data: queryData,
                beforeSend: function () {
                    //弹出加载中
                    index = layer.load(1, {
                        shade: [0.3, '#000'] //0.1透明度的白色背景
                    });
                },
                success: function (data) {
                    checkRows.data = data;
                    table.exportFile(tableResult.config.id, checkRows.data, 'xls');                    layer.close(index);
                },
                error: function (data) {
                    console.log(data)
                }
            });
        }
    };
    var sl = {
        goodsNum: "",
        putNum: "",
        putVolume: "",
        realNum: "",
    };

    // 发送 AJAX 请求获取合计数据
    $.ajax({
        url:Feng.ctxPath + '/hxStoragePut/count',
        dataType: "json",
        async: false,
        type: "post",
        success: function (data) {
            console.log(data);
            sl = data.data;
            console.log(sl);
        },
        error: function (xhr, status, error) {
            console.error("请求失败：", status, error);

        }
    });
    // 渲染表格
    var tableResult = table.render({
        elem: '#' + HxStoragePut.tableId,
        url: Feng.ctxPath + '/hxStoragePut/list',
        toolbar: '#toolbarfrom',
        cellMinWidth: 100,
        totalRow: true ,//开启合计行
        cols: HxStoragePut.initColumn()
        ,parseData: function(res){ // 数据转换
            return {
                "code": 0,
                "msg": res.msg, // 假设原数据中的msg字段存储的是提示信息
                "count": res.count,
                "data": $.map(res.data, function(item){ // 假设原数据中的data字段存储的是数据集
                    return {
                        // 假设你想转换的字段是numberField
                        putNum: Number(item.putNum), // 将字符串转换为数字
                        realNum: Number(item.realNum), // 将字符串转换为数字
                        // 其他字段保持不变
                        id: item.id,
                        customerName: item.customerName,
                        storageState: item.storageState,
                        yuyueTime: item.yuyueTime,
                        storageNumber: item.storageNumber,
                        orderType: item.orderType,
                        getWarehouse: item.getWarehouse,
                        setUnit: item.setUnit,
                        goodsNum: item.goodsNum,

                        putVolume: item.putVolume,
                        createTime: item.createTime,
                        createUserName: item.createUserName,
                        completeTime: item.completeTime,
                        notes: item.notes
                    };
                })
            };
        },
        page: true,
        limit: 40,
        height: 410,
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        HxStoragePut.search();
    });

    $('#reset').click(function () {
        $("#setUnit").val("")
        $("#condition").val("")
        $("#goodsName").val("")
    });

    // 导出excel
    $('#btnExp').click(function () {
        HxStoragePut.exportExcel();
    });

    /**
     * 初始化表格的列
     */
    HxStoragePutDetailed.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: '主键id'},
            {field: 'trayNumber', sort: true, title: '托盘编号'},

            {field: 'goodsName', sort: true, title: '商品名称', width: 160},
            {field: 'goodsNumber', sort: true, title: '商品编号'},
            {field: 'goodsPcode69', sort: true, title: '商品码'},
            {field: 'goodsSpecs', sort: true, title: '规格'},
            {field: 'unit', sort: true, title: '单位', totalRowText: '合计：'},

            {field: 'num', sort: true, title: '数量', totalRow: true},
            {field: 'realNum', sort: true, title: '实际数量', totalRow: true},
            {field: 'jibenUnit', sort: true, title: '基本单位'},
            {field: 'jibenNum', sort: true, title: '基本数量'},
            {field: 'jibenRealNum', sort: true, title: '实际基本数量'},

            {field: 'goodsWeight', sort: true, title: '重量'},
            {field: 'putWeight', sort: true, title: '应入重量', totalRow: true},
            {field: 'goodsVolume', sort: true, title: '体积'},
            {field: 'putVolume', sort: true, title: '应入体积', totalRow: true},
            {field: 'goodsPrice', sort: true, title: '单价'},
            {field: 'putMoney', sort: true, title: '金额', totalRow: true},

            {field: 'detailedDate', sort: true, title: '生产日期'},

            {field: 'putState', sort: true, title: '入库状态', templet: '#putStateTpl'},
            {field: 'qualityUserName', sort: true, title: '质检人'},
            {field: 'qualityTime', sort: true, title: '质检时间'},
            {field: 'putUserName', sort: true, title: '上架人'},
            {field: 'putTime', sort: true, title: '上架时间'},
            {field: 'positionNumber', sort: true, title: '上架库位'}
        ]];
    };

    // 单击行事件
    table.on('row(' + HxStoragePut.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + HxStoragePut.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + HxStoragePut.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        hxStoragePut(data);
    });
    
    function hxStoragePut(data){
    	var storageNumber;
    	if (data!=null) {
    		storageNumber = data.storageNumber;
		} else {
			storageNumber = '0';
		}
        // 渲染商品明细表格
        var tableResult = table.render({
            elem: '#' + HxStoragePutDetailed.tableId,
            url: Feng.ctxPath + '/hxStoragePutDetailed/list?storageNumber=' + storageNumber,
            page: true,
            limit: 120,
            limits:[60,120,240,360,480],
            height: 400,
            toolbar: '#toolbarfromDetailed',
            cellMinWidth: 100,
            totalRow: true ,//开启合计行
            cols: HxStoragePutDetailed.initColumn()
        });

        /**
         * 点击查询按钮
         */
    	HxStoragePutDetailed.search = function () {
            var queryData = {};
            queryData['condition'] = $("#condition2").val();
            table.reload(HxStoragePutDetailed.tableId, {
                where: queryData, page: {curr: 1},
                 done:function () {
                     // 搜索按钮点击事件
                     $('#btnSearchDetailed').click(function () {
                    	 HxStoragePutDetailed.search();
                     });
                }
            });
        };

        // 搜索按钮点击事件
        $('#btnSearchDetailed').click(function () {
        	HxStoragePutDetailed.search();
        });

    }
});
